const fs = require('fs')
const path = require('path')

class ManifestPlugin {
  apply(compiler) {
    compiler.hooks.emit.tapAsync('ManifestPlugin', (compilation, callback) => {
      const files = {}
      for (const chunk of compilation.chunks) {
        files[chunk.name] = {
          styles: [...chunk.files].filter(item => item.endsWith('.css')).map(item => '/' + item),
          scripts: [...chunk.files].filter(item => item.endsWith('.js')).map(item => '/' + item)
        }
      }
      fs.writeFileSync(path.join(compiler.outputPath, '../manifest.json'), JSON.stringify(files, null, 2))
      callback()
    })
  }
}

module.exports = ManifestPlugin
